package com.ynu.springbootappdemo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket")
@Slf4j
public class WebSocketService {
    //连接会话
    private Session session;

    //会话存储
    private static final CopyOnWriteArraySet<WebSocketService> webSocketServiceSet = new CopyOnWriteArraySet<>();

    //连接
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketServiceSet.add(this);
        log.info("【websocket消息】有新的连接，总数:{}", webSocketServiceSet.size());
    }

    //关闭
    @OnClose
    public void onClose() {
        webSocketServiceSet.remove(this);
        log.info("【websocket消息】连接断开，总数:{}", webSocketServiceSet.size());}

    //消息群发
    public void sendMessage(String message) {
        for (WebSocketService webSocketService : webSocketServiceSet) {
            webSocketService.session
                    .getAsyncRemote()
                    .sendText(message);
        }
        log.info("【websocket消息】发送消息:{}", message);
    }

}
